package com.weiaibenpao.demo.chislim.sport;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.RunningPreferences;
import com.weiaibenpao.demo.chislim.bean.UserBean;
import com.weiaibenpao.demo.chislim.hurui.activity.HBaseActivity;
import com.weiaibenpao.demo.chislim.sport.bean.ProvinceBean;
import com.weiaibenpao.demo.chislim.sport.bean.RegionBean;
import com.weiaibenpao.demo.chislim.sport.bean.RegionDataBean;
import com.weiaibenpao.demo.chislim.sport.utils.JsonProvinceUtils;
import com.weiaibenpao.demo.chislim.sport.utils.PolyLines;
import com.weiaibenpao.demo.chislim.util.DateUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.weiaibenpao.demo.chislim.sport.utils.Constant.SPORT_TYPE;
import static com.weiaibenpao.demo.chislim.sport.utils.PolyLines.POLYLINE_OVER_SUCCESS;


public class RegionActivity extends HBaseActivity {
    private String location = null;
    private double perimeter;
    private String code = "";
    @BindView(R.id.region_back)
    ImageView backImg;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.my_history_record)
    TextView myHistoryRecord;
    @BindView(R.id.topLayout)
    RelativeLayout topLayout;
    @BindView(R.id.region_mv)
    MapView mapView;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.choose_city_btn)
    Button chooseCityBtn;
    @BindView(R.id.tv_region_distance)
    TextView tvRegionDistance;
    @BindView(R.id.tv_run_distance)
    TextView tvRunDistance;
    @BindView(R.id.tv_run_time)
    TextView tvRunTime;
    @BindView(R.id.goon_run_btn)
    Button goonRunBtn;
    private int type = 2;
    AMap aMap = null;
    int num = 0; //总点数
    private String provinceName = "";
    private String cityName = "";
    private String districtName = "";
    private String selectName;
    private int idCode;
    private PolyLines polyline;
    private RegionDataBean bean;
    private PolylineOptions options;
    int num1 = 0;
    int num2 = 0;
    int num3 = 0;
    DecimalFormat decimalFormat = new DecimalFormat("0.00");
    private UserBean userBean;
    private PolylineOptions polylineOption2;
    private JsonProvinceUtils jsonProvinceUtils;
    private ArrayList<com.weiaibenpao.demo.chislim.sport.bean.ProvinceBean> options1Items;
    private ArrayList<ArrayList<String>> options2Items;
    private ArrayList<ArrayList<ArrayList<String>>> options3Items;
    private RunningPreferences preferences;
    private OptionsPickerView pvOptions;
    WeakReference<Activity> weakReference = new WeakReference<Activity>(this);
    Context context;
    private boolean isStartPointDrawn = false;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case POLYLINE_OVER_SUCCESS:
                    options = (PolylineOptions) msg.obj;
                    num = options.getPoints().size();

                    if (bean != null && bean.getTotalDistance() != 0) {
                        drawLines(bean.getTotalDistance(), bean.getYudingDistance());
                    }
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_region);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.ku_bg), 0);
        EventBus.getDefault().register(this);
        context = weakReference.get();
        type = getIntent().getIntExtra(SPORT_TYPE, 2);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.ku_bg), 0);
        userBean = UserBean.getUserBean();
        mapView.onCreate(savedInstanceState);
        jsonProvinceUtils = new JsonProvinceUtils(this);
        jsonProvinceUtils.initJsonData();
        initMap();
        addCity("", 1);
    }


    /**
     * 查询和添加城市
     *
     * @param code
     * @param type
     */
    private void addCity(final String code, final int type) {

        apiStores.getselectSport(userBean.userId, code).enqueue(new Callback<RegionBean>() {
            @Override
            public void onResponse(Call<RegionBean> call, Response<RegionBean> response) {
                Log.e("lfy", "addCity: " + new Gson().toJson(response));
                if (response.body() == null)
                    return;
                if (response.body().getData() != null) {
                    bean = response.body().getData();
                    initView(type);
                } else {
                    initBean();

                }

            }

            @Override
            public void onFailure(Call<RegionBean> call, Throwable throwable) {
                Toast.makeText(context, throwable.getMessage(), Toast.LENGTH_SHORT);
            }
        });
    }

    /**
     * 查询数据为空时 ，需要造一条数据
     */
    private void initBean() {
        tvRunDistance.setText("0");
        tvRunTime.setText("00:00:00");
        goonRunBtn.setText("去跑步");
        goonRunBtn.setClickable(true);
//        String area, double yudingDistance, String city, int xingzhengId, String province, String code

    }

    protected void initView(int type) {

        if (type == 1) {
            provinceName = bean.getProvince();
            cityName = bean.getCity();
            districtName = bean.getArea();
            if (TextUtils.isEmpty(cityName)) {
                selectName = bean.getProvince();
                tvLocation.setText(bean.getProvince());
                tvRegionDistance.setText(bean.getYudingDistance() + "");
            } else if (TextUtils.isEmpty(districtName) && !TextUtils.isEmpty(cityName)) {
                selectName = bean.getCity();
                tvLocation.setText(bean.getProvince() + "·" + bean.getCity());
            } else {
                selectName = bean.getArea();
                tvLocation.setText(bean.getProvince() + "·" + bean.getCity() + "·" + bean.getArea());

            }
            polyline.drawLIne(bean.getCode(), selectName, handler);
        }

        tvRegionDistance.setText( decimalFormat.format(bean.getYudingDistance()));
        tvRunDistance.setText( decimalFormat.format(bean.getTotalDistance()));
        tvRunTime.setText(DateUtil.getFormatTime(bean.getTotalTime()));
        if (bean.getTotalDistance() >= bean.getYudingDistance()) {
            goonRunBtn.setText("已跑完");
            polyline.setColor(Color.parseColor("#cc358f"));
            polyline.drawLIne(code, selectName, handler);
            goonRunBtn.setClickable(false);
        } else if (bean.getTotalDistance() == 0) {
            goonRunBtn.setText("去跑步");
            goonRunBtn.setClickable(true);
        } else if (bean.getTotalDistance() < bean.getYudingDistance()) {
            goonRunBtn.setText("继续跑");
            goonRunBtn.setClickable(true);
        }


    }

    /**
     * 绘制轨迹
     */
    int h = 0;

    public void drawLines(double dis, double totalDis) {//dis  单位米


        if (dis >= totalDis) {
            h = num;
        } else {
            h = (int) (num * (dis / totalDis));
            Log.i("行政区划", "---------" + dis / totalDis);
        }
        for (int m = 0; m < h; m++) {
            //updateCamera(((LatLng)arrayList.get(m)).latitude,((LatLng)arrayList.get(m)).longitude);            //设置地图中心点
            polylineOption2.add(options.getPoints().get(m));

        }
        if (options.getPoints().size() != 0)
            setMarkView(options.getPoints().get(0));
        aMap.addPolyline(polylineOption2);


    }

    //设置起点
    private void setMarkView(LatLng latLng) {
        View view = View.inflate(context, R.layout.mark_layout, null);
        TextView sportMark = (TextView) view.findViewById(R.id.sportTitle);
        sportMark.setText("起");
        Bitmap bitmap = convertViewToBitmap(view);
        drawMarkerOnMap(latLng, bitmap, String.valueOf("起"));
        isStartPointDrawn = true;
    }

    public static Bitmap convertViewToBitmap(View view) {

        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

        view.buildDrawingCache();

        Bitmap bitmap = view.getDrawingCache();

        return bitmap;
    }

    /**
     * 在地图上画marker
     *
     * @param point      marker坐标点位置（example:LatLng point = new LatLng(39.963175,
     *                   116.400244); ）
     * @param markerIcon 图标
     * @return Marker对象
     */
    private Marker drawMarkerOnMap(LatLng point, Bitmap markerIcon, String id) {

        if (aMap != null && point != null) {

            Marker marker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 1)
                    .position(point)
                    .title(id)
                    .icon(BitmapDescriptorFactory.fromBitmap(markerIcon)));
            return marker;
        }
        return null;
    }

    private void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        aMap.setTrafficEnabled(false);           // 显示实时交通状况
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE(卫星图),MAP_TYPE_NIGHT(夜景地图)
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 地图模式

        polyline = new PolyLines(context, aMap);
        options1Items = jsonProvinceUtils.getOptions1Items();
        options2Items = jsonProvinceUtils.getOptions2Items();
        options3Items = jsonProvinceUtils.getOptions3Items();
        if (polylineOption2 == null) {
            polylineOption2 = new PolylineOptions();
            polylineOption2.width(12).color(Color.parseColor("#cc358f"));
        }
    }


    public static void openActivity(Context context, int type) {
        Intent intent = new Intent(context, RegionActivity.class);
        intent.putExtra(SPORT_TYPE, type);
        context.startActivity(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
//        initData();

    }

    @Subscribe
    public void onMessageEvent(Boolean flag) {
        if (flag) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mapView.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        mapView.onSaveInstanceState(outState);
    }

    @OnClick({R.id.region_back, R.id.my_history_record, R.id.choose_city_btn, R.id.goon_run_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.region_back:
                finish();
                break;
            case R.id.my_history_record:
                RegionRecordActivity.openActivity(context, type);
                break;
            case R.id.choose_city_btn:
                showPickerView();


                break;
            case R.id.goon_run_btn:
                if (tvLocation.getText().toString().trim().equals("请选择城市")) {
                    goonRunBtn.setClickable(false);
                    Toast.makeText(context, "请选择城市", Toast.LENGTH_SHORT).show();
                } else {
                    goonRunBtn.setClickable(true);

                    startRun();
                }
                break;
        }
    }

    private void startRun() {

        if (type == 2) {
            if (bean == null) {
                bean = new RegionDataBean(districtName, perimeter, cityName, 0, provinceName, code);
            }
            SportHomeDistrictActivity.openActivity(this, bean, selectName);
        } else if (type == 3) {
            preferences = RunningPreferences.getInstance();
            preferences.setDistrict(provinceName + "," + cityName + "," + districtName);
            if (bean == null) {
                bean = new RegionDataBean(districtName, perimeter, cityName, 0, provinceName, code);
            }
            preferences.setDistrictTotalDistance(bean.getTotalTime());
            preferences.setDistrictCode(bean.getCode());
            preferences.setDistrictTotalDistance((float) bean.getTotalDistance());
            preferences.setDistrictID(bean.getId());
            preferences.setDistrictTotalTime(bean.getTotalTime());
            preferences.setDistrictDistance((float) bean.getYudingDistance());
            preferences.setDistrictSelect(selectName);
            SportOutDistrictActivity.openActivity(this, bean, selectName);
        }
        finish();
    }

    public void showPickerView() {

        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                polyline.setColor(Color.parseColor("#189ff6"));
                provinceName = options1Items.get(options1).getPickerViewText();
                cityName = options2Items.get(options1).get(options2);
                districtName = options3Items.get(options1).get(options2).get(options3);
                num1 = options1;
                num2 = options2;
                num3 = options3;
                ProvinceBean provinceBean = options1Items.get(options1);
                if (cityName.equals("全部")) {
                    location = provinceName;
                    cityName = "";
                    districtName = "";
                    selectName = provinceName;
                    perimeter = Double.parseDouble(options1Items.get(options1).getProvincePerimeter());
                    code = provinceBean.getProvinceCode();

                } else if (districtName.equals("全部")) {
                    ProvinceBean.CitylistBean citylistBean = provinceBean.getCitylist().get(options2);
                    location = provinceName + "·" + cityName;
                    districtName = "";
                    selectName = citylistBean.getCityKey();
                    perimeter = Double.parseDouble(citylistBean.getCityPerimeter());
                    code = citylistBean.getCityCode();


                } else {
                    ProvinceBean.AreaListBean areaListBean = options1Items.get(options1).getCitylist().get(options2).getAreaList().get(options3);
                    location = provinceName + "·" + cityName + "·" + districtName;
                    selectName = districtName;
                    perimeter = Double.parseDouble(areaListBean.getAreaPerimeter());
                    code = areaListBean.getAreaCode();

                }
//                polyline.getLatlon(cityName,districtName);
                tvLocation.setText(location);
                tvRegionDistance.setText(decimalFormat.format(perimeter) + "");
                bean = null;
                addCity(code, 2);
                if (polylineOption2.getPoints()!=null){
                    polylineOption2.getPoints().clear();
                }
                polyline.drawLIne(code, selectName, handler);

//                Log.e("tvRegionDistance", "onOptionsSelect: "+tvRegionDistance.getText().toString() );
//                tvRegionDistance.setText(tvRegionDistance.getText().toString());

            }
        }).setTitleText(" ")
                .setDividerColor(Color.BLACK)
                .setOutSideCancelable(true)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setSubmitColor(Color.parseColor("#333333"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#666666"))//取消按钮文字颜色
                .setLineSpacingMultiplier(2.0f)
                .setSelectOptions(num1, num2, num3)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


}
